package com.tianji.learning.mq;

import com.tianji.api.constants.CourseStatus;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.entity.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.service.ILearningLessonService;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Component
@RequiredArgsConstructor  // 方便注入
public class LessonDeleteListener {
    private final ILearningLessonService lessonService;

    /*MqConstants.Exchange.ORDER_EXCHANGE,
      MqConstants.Key.ORDER_REFUND_KEY*/
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue",durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))

    @Transactional
    public void listenLessonRefund(OrderBasicDTO orderBasicDTO){
        // 1.判空处理
        if (orderBasicDTO == null || orderBasicDTO.getUserId() == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds())){
            // 数据有误，直接结束
            log.error("接收到的mq消息有误，订单数据为空");
            return;
        }

        // 2.修改退款后的课程状态为 已过期
        lessonService.lambdaUpdate()
                .set(LearningLesson::getStatus,LessonStatus.EXPIRED.getValue())
                .eq(LearningLesson::getUserId,orderBasicDTO.getUserId())
                .in(LearningLesson::getCourseId,orderBasicDTO.getCourseIds())
                .update();

        // 3.删除课程
        log.debug("监听到用户{}的订单{}。删除课程{}，",orderBasicDTO.getUserId(),orderBasicDTO.getOrderId(),orderBasicDTO.getCourseIds());
        lessonService.deleteUserLesson(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }
}
